// Function to update the declarativeNetRequest rules
const updateRules = (rules) => {
  const newRules = rules
    .filter(rule => rule.enabled && rule.from && rule.to)
    .map((rule, index) => ({
      id: index + 1, // Rules must have a unique ID > 0
      priority: 1,
      action: {
        type: 'redirect',
        redirect: {
          transform: {
            scheme: 'http',
            host: rule.to.split(':')[0],
            port: rule.to.split(':')[1] || '',
          },
        },
      },
      condition: {
        urlFilter: `*://${rule.from}/*`,
        resourceTypes: ['main_frame', 'sub_frame', 'stylesheet', 'script', 'image', 'object', 'xmlhttprequest', 'other'],
      },
    }));

  chrome.declarativeNetRequest.getDynamicRules((existingRules) => {
    const existingRuleIds = existingRules.map(rule => rule.id);
    chrome.declarativeNetRequest.updateDynamicRules({
      removeRuleIds: existingRuleIds,
      addRules: newRules,
    });
  });
};

// Listen for initial state from storage
chrome.storage.sync.get('rules', (data) => {
  if (data.rules) {
    updateRules(data.rules);
  }
});

// Listen for changes from the popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'SET_RULES') {
    updateRules(message.rules);
  }
  // The GET_STATE and SET_ENABLED messages are now handled directly by the popup
  // as the background script is a service worker and may not always be active.
});